package com.catchegg.springcloud.controller;

import com.catchegg.springcloud.entities.CommonResult;
import com.catchegg.springcloud.entities.Payment;
import com.catchegg.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author noreply
 * @description
 * @datetime 2021/11/1 20:04
 */
@RestController
@Slf4j
public class PaymentController {
    @Resource
    private PaymentService paymentService;

    @Resource
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String port;

    @PostMapping("/payment/create")
    public CommonResult create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        log.info("insert result: {}", result);
        if (result > 0) {
            return new CommonResult(200, "success", result);
        } else {
            return new CommonResult(444, "fail", null);
        }
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);
        log.info("get result: {}", payment);
        return new CommonResult(200, "success" + port, payment);
    }

    @GetMapping("/payment/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        String description = discoveryClient.description();
        int order = discoveryClient.getOrder();
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");

        Map<String, Object> result = new HashMap<>(8);
        result.put("services", services);
        result.put("description", description);
        result.put("order", order);
        result.put("instances", instances);
        return result;

    }

    @GetMapping("/payment/lb")
    public Object lb() {
        return port;
    }

    @GetMapping("/payment/feign/timeout")
    public Object feignTimeout() {
        try {
            Thread.sleep(3 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return port;
    }

}
